package com.ztz.mynewdemo.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SignUpCallback;
import com.ztz.mynewdemo.MainActivity;
import com.ztz.mynewdemo.MyDbHelper;
import com.ztz.mynewdemo.R;
import com.ztz.mynewdemo.utils.AppStringUtils;
import com.ztz.mynewdemo.utils.KeyBoardUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by wqewqe on 2018/1/8.
 */

public class RegisterFragment extends Fragment {
    private static final String TAG = "RegisterFragment";
    @BindView(R.id.et_registerName)
    EditText etRegisterName;
    @BindView(R.id.et_registerPwd)
    EditText etRegisterPwd;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    Unbinder unbinder;
    MyDbHelper dbHelper;
    View mProgressView;
    View mRegisterView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dbHelper = new MyDbHelper(getActivity(), "UserInfoStore.db", null, 2);
        mProgressView = view.findViewById(R.id.register_progressBar);
        mRegisterView = view.findViewById(R.id.register_form);
        etPwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    attemptRegister();
                    KeyBoardUtils.closeKeyBoard(getActivity(),etPwd);
                    return true;
                }
                return false;
            }
        });
        KeyBoardUtils.openKeyBoard(getActivity(),etRegisterName);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.btn_register,R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_register:
                ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                Boolean isWifiConn = networkInfo.isConnected();

                //获取移动数据连接的信息
                networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                Boolean isMobileConn = networkInfo.isConnected();
                if(isWifiConn||isMobileConn){
                    attemptRegister();
                }else {
                    Toast.makeText(getActivity(), "请打开网络连接", Toast.LENGTH_SHORT).show();
                }
                KeyBoardUtils.closeKeyBoard(getActivity(),etPwd);
                break;
            case R.id.tv_login:
                getFragmentManager().popBackStack();
                break;
        }
    }

    private void attemptRegister() {
        String regName = etRegisterName.getText().toString();
        String regPwd = etRegisterPwd.getText().toString();
        String edPwd = etPwd.getText().toString();
        boolean cancel = false;
        View focusView = null;
        if (!AppStringUtils.checkName(regName)) {
            etRegisterName.setError("用户名不能为空，并且不能小于3位，大于10位");
            cancel = true;
            focusView = etRegisterName;
        } else if (!AppStringUtils.checkPassword(regPwd)) {
            etRegisterPwd.setError("密码不能为空，并且不能小于4位，大于10位");
            cancel = true;
            focusView = etRegisterPwd;
        } else if (!AppStringUtils.checkPassword(regPwd, edPwd)) {
            etPwd.setError("两次输入密码不一致");
            cancel = true;
            focusView = etPwd;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            ShowProgress(true);
//            UserRequest userRequest = new UserRequest(regName, edPwd);
//            Request request = RequestUtils.requestPOST(userRequest, NewsApi.URL.REGISTER);
//            OkHttpClient okHttpClient = new OkHttpClient();
//            okHttpClient.newCall(request).enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//
//                }
//
//                @Override
//                public void onResponse(Call call, final Response response) throws IOException {
//                    final String result = response.body().string();
//                    Log.i(TAG, "onResponse: " + result);
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (response.code() == 201) {
//                                Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
//                                getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
//                                getActivity().finish();
//                            } else {
//                                ShowProgress(false);
//                                ErrorResponse errorResponse = new Gson().fromJson(result, ErrorResponse.class);
//                                if (errorResponse.getCode() == 202) {
//                                    Toast.makeText(getActivity(), "用户名已存在", Toast.LENGTH_SHORT).show();
//                                } else {
//                                    Toast.makeText(getActivity(), "注册失败", Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        }
//                    });
//                }
//            });
            AVUser avUser = new AVUser();
            avUser.setUsername(regName);
            avUser.setPassword(edPwd);
            avUser.signUpInBackground(new SignUpCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        //注册成功，把对象值赋值给当前用户 AVUser.getCurrentUser()
                        getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
                        getActivity().finish();
//                        Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
                    } else {
                        ShowProgress(false);
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        ContentValues values = new ContentValues();
//        values.put("userName", regName);
//        values.put("password", regPwd);
//        long id = db.insert("UserInfo", null, values);
//        if (id != -1) {
//            Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
//        } else {
//            Toast.makeText(getActivity(), "注册失败", Toast.LENGTH_SHORT).show();
//        }
//        SharedPreferences.Editor editor=getActivity().getSharedPreferences("data", Context.MODE_APPEND).edit();
//        editor.putString("name",regName);
//        editor.putString("pwd",regPwd);
//        editor.apply();
    }

    private void ShowProgress(final boolean show) {

        int shortAnimTime = getResources().getInteger(android.R.integer.config_longAnimTime);
        mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
        mRegisterView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
                    }
                });
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                    }
                });


    }

    @Override
    public void onPause() {
        super.onPause();
        AVAnalytics.onPause(getActivity());
    }

    @Override
    public void onResume() {
        super.onResume();
        AVAnalytics.onResume(getActivity());
    }
}
